<?php require('../include/init.php'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<?php
		include('PHPExcel/IOFactory.php');
		/**
		 *  如果需要导入年月日的时候采用，第一参数是PHPExcel取出来的，第二参数给false就行了
		 */
		
		$lnk =mysql_connect($db_host,$db_user,$db_pass)or die ('Not connected : ' . mysql_error());
				// make foo the current db
		mysql_select_db($db_name, $lnk) or die ('Can\'t use zy-sms : ' . mysql_error());
		/**获取为分组ID*/
			$sql="select * from zy_contact_list  where  company_id=".$_SESSION['user']['customer']->company_id." ORDER BY contact_list_id ASC";
			$contact_list_id=$GLOBALS['mysql']->select($sql);
			/**获取值*/
			$company_id=$_SESSION['user']['customer']->company_id;
			$department_id=$_SESSION['user']['customer']->department_id;
			$user_id=$_SESSION['user']['customer']->user_id;
			$contact_create_time=date('Y-m-d H:i:m');
			$contact_update_time=date('Y-m-d H:i:m');
			$group=$_POST['contact_list_id'];
			if(!empty($group)){
				$set=implode(']|[',$group);
			}
			else{
			 	$set=$contact_list_id[0]->contact_list_id;
			}
		function excelTime($days) { 
			//把phpexcel读出的日期数据转换成xxxx-m-y
			if (is_numeric($days)) {
				$jd = GregorianToJD(1, 1, 1970);
				$gregorian = JDToGregorian($jd +intval($days) - 25569);
				$myDate = explode('/', $gregorian);
				$myDateStr = str_pad($myDate[2], 4, '0', STR_PAD_LEFT) .
				"-" . str_pad($myDate[0], 2, '0', STR_PAD_LEFT) .
				"-" . str_pad($myDate[1], 2, '0', STR_PAD_LEFT) ;
				return $myDateStr;
			}else{
				$myDate = explode('-', $days);
				$myDateStr ="20".$myDate[0]."-".$myDate[2]."-".$myDate[1];
				return $myDateStr;
			}
		}
		  
		chdir(dirname(__FILE__));
		
			function upload_files($filespath)
		     {
		       $name=$filespath["name"];
		       $tmp_name=$filespath["tmp_name"];
		       $size=$filespath["size"];
		       $uploadfile = "excelFile/".date("YmdHis")."_".$filespath['name'];
				if($name=="")                                             //文件名为空
				  {
					echo"<script>alert('Please select a file to upload!'); 
						 window.history.back();</script>";
				  }
				$file = explode("|", "xls|xlsx|csv");
				$upload_file = strtolower(end(explode(".", $_FILES['file']['name'])));
				if(!in_array($upload_file,$file)){
				echo"<script type='text/javascript'>alert('Hello, can only import EXCEL file!');window.history.back();</script>";
				exit;
					}
			  if(move_uploaded_file($tmp_name,$uploadfile))
				return $uploadfile;
			  else if (copy($tmp_name,$uploadfile))
				return $uploadfile;
			  else
			   return false;
			 	}
			 
			$excFile=$_FILES['file'];
			$aa=upload_files($excFile);
			$upload_file = strtolower(end(explode(".", $_FILES['file']['name'])));
			if($upload_file=='xls'){
				$reader = PHPExcel_IOFactory::createReader('Excel5'); // 2007以下用:Excel5 ，  2007用：Excel2007
				}elseif($upload_file=='csv'){
					$reader=PHPExcel_IOFactory::createReader('csv');
				}else{
				$reader = PHPExcel_IOFactory::createReader('Excel2007'); // 2007以下用:Excel5 ，  2007用：Excel2007
				}
				
			$PHPExcel = $reader->load($aa);
			$sheet = $PHPExcel->getSheet(0); // 读取第一个工作表(编号从零开始。) 
			
			$highestRow = $sheet->getHighestRow(); // 取得总行数
			$highestColumn = $sheet->getHighestColumn();
			
			$array=array('A'=>'1','B'=>'2','C'=>'3','D'=>'4','E'=>'5','F'=>'6'
			
			,'G'=>'7','H'=>'8','I'=>'9','J'=>'10','K'=>'11','L'=>'12'
			
			,'M'=>'13','N'=>'14','O'=>'15','P'=>'16','Q'=>'17','R'=>'18'
			
			,'S'=>'19');//定义一个列数数组，默认从1开始
			$bColumn=-1;
		    $name="";//初始化列表名
			for($row=1;$row<=$highestRow;$row++){//从第3行开始   1	  2
			$sql='';//初始化sql变量	
			$str_flag="-1";
			for ($column =0; $column<$array[$highestColumn];$column++) { //列数
					$value=$sheet->getCellByColumnAndRow($column, $row)->getValue();
					$str_flag.=$value;
						if($column==6){
							if($value=="")
								$value="0000-00-00";
							else
								$value=excelTime($value);
						}
						$val=trim($value);
						$sql.="'$val',";
						
			   }
			   
			   
			   if($row != 1){
			   	if(trim($str_flag)!="-1"){
			   		  $sqls="INSERT INTO zy_contact(contact_first_name,contact_surname,contact_email,contact_mobile,contact_phone,contact_title,contact_birth_date,contact_address,contact_remark, company_id,department_id,user_id,contact_create_time,contact_update_time,contact_list) VALUES($sql '$company_id','$department_id','$user_id','$contact_create_time','$contact_update_time','[$set]')";
					    $res=$GLOBALS['mysql']->insert($sqls,true);
					    $updateContactListCountSql="update zy_contact_list set contact_list_count=contact_list_count+1 where contact_list_id=".$contact_list_id[0]->contact_list_id;
					    $GLOBALS['mysql']->upadte($updateContactListCountSql);
			   	}
			   }
			}
				if($res>0){
				echo "<script>alert('Import the data successfully!');window.history.back();</script>";
				}else{
					echo "<script>alert('Failed to import data!');window.history.back();</script>";
					}
		?>